<?php
/*
 * HSBC Payment Plugin Class
 */
class RM_Plugin_HSBC extends RM_Payments_Plugin
{    
    /**
     * distination for posting the payment data
     * @var sting
     */
    private $_live_post_url = "https://www.secure-epayments.apixml.hsbc.com";
    private $_test_post_url = "https://www.uat.apixml.secureepayments.hsbc.com";

    private $_ipnLog = false; // logging enabled

    private $_test_mode = false; // test mode enabled

    /**
     * Public constructor
     */
    public function  __construct() {
        $this->name = 'HSBC';
        $this->_ipnLogFile = RM_Environment::getConnector()->getCorePath().DIRECTORY_SEPARATOR.'userdata'.DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'HSBC_log.txt';

        
    }

    /**
     * collects the payment data and sends to Authrize.net
     */
    public function Process($bookingRef, $ccArray, $userData){

        if (empty($ccArray) || empty($userData)) return false;

        $settings = $this->_getConfig();
        
        if ($setting['preauth_mode'] === "" || $setting['preauth_mode'] == true){
            $authmode = "PreAuth";
        } else {
            $authmode = "Auth";
        }

        $testmode = "P"; // live mode
        $url = $this->_live_post_url;
        if ($this->_test_mode){
            $testmode = "Y";
            $url = $this->_test_post_url;
        }

        $config = new RM_Config();
        $currencyCode = $config->getValue('rm_config_currency_iso');
        $converterObject = new RM_HSBC_Codes();
        $currencyISO4217 = $converterObject->convert($currencyCode);


        $xml =  '<?xml version="1.0" encoding="UTF-8" ?>
                  <EngineDocList>
                    <DocVersion DataType="String">1.0</DocVersion>
                    <EngineDoc>
                      <ContentType DataType="String">OrderFormDoc</ContentType>
                      <User>
                        <ClientId DataType="S32">'.$settings['client_id'].'</ClientId>
                        <Name DataType="String">'.$settings['user_id'].'</Name>
                        <!-- Name is case sensitive -->
                        <Password DataType="String">'.$settings['password'].'</Password>
                        <!-- Password is case sensitive -->
                      </User>
                      <Instructions>
                        <Pipeline DataType="String">Payment</Pipeline>
                        <!-- Set Pipeline to Payment to benefit from HSBC fraud rule protection, see the guide for alternate values -->
                      </Instructions>
                      <OrderFormDoc>
                        <Id DataType="String">'.$bookingRef.'</Id>
                        <!-- Id is optional, but if supplied must be a unique value -->
                        <Mode DataType="String">'.$testmode.'</Mode>
                        <!-- Set Mode to P (Production) for REAL transactions, see the guide for alternate values -->
                        <Consumer>
                          <PaymentMech>
                            <Type DataType="String">CreditCard</Type>
                            <!-- Type is always set to CreditCard -->
                            <CreditCard>
                              <Number DataType="String">'.$ccArray['x_card_num'].'</Number>
                              <Expires DataType="ExpirationDate" Locale="826">'.$ccArray['x_exp_date'].'</Expires>
                              <!-- Expires with Locale 826 represents mm/yy format -->
                            </CreditCard>
                          </PaymentMech>
                        </Consumer>
                        <Transaction>
                          <Type DataType="String">'.$authmode.'</Type>
                          <CurrentTotals>
                            <Totals>
                              <Total DataType="Money" Currency="'.$currencyISO4217.'">'.$ccArray['x_amount'].'</Total>
                              <!-- Total with Currency 826 represents values in pence -->
                            </Totals>
                          </CurrentTotals>
                        </Transaction>
                      </OrderFormDoc>
                    </EngineDoc>
                  </EngineDocList>';

        // send the request with the data...
        $client = new Zend_Http_Client($url);
        $response = $client->setRawData($xml, 'text/xml')->request('POST');
        $responseXML = $response->getBody();
        $response_array = $this->parseResponse($responseXML);

        $this->_logResults("------ Transaction Started ------");

        if (isset($response_array['TEXT']) && (int)$response_array['STATUS']!==1){
            $msg = $response_array['TEXT'];
        } else {
            $msg = $response_array['PROCRETURNMSG'];
        }
        
        $responseData['ResponseCode'] = (int)$response_array['STATUS'];
        $responseData['ResponseReasonCode'] = $response_array['STATUS'];
        $responseData['ResponseReasonText'] = $msg;
        $responseData['AuthorizationCode'] = $response_array['AUTHCODE'];
        $responseData['TransactionID'] = $response_array['TRANSACTIONID'];
        $responseData['BookingRef'] = $response_array['ORDERID'];
        $responseData['Amount'] = $response_array['TOTAL'];
        $responseData['TransactionType'] = $response_array['TYPE'];
        
        foreach ($responseData as $key=>$value){
            $this->_logResults($key.": ".$value);
        }
        $this->_logResults("------ Transaction Ended ------");

        // now send back the response...
        return $responseData;
    }

    /**
     * We don't need to present this plugins under admin tree menu 'Plugins', only on Config leaf
     * 
     * @return null
     */
    public function getNode(){
        return null;
    }


    /**
     * get the HSBC config
     *
     * @return   array
     */
    private function _getConfig() {
        $HSBCObj = new RM_HSBC;
        $value = $HSBCObj->getSettings()->toArray();
        return $value[0];
    }

    /**
     * used to log results to the ipn log file so we can see whats happening
     *
     * @param boolean $success if this is a successful or fail log
     */
    private function _logResults($msg)
    {
        if (!$this->_ipnLog) return;  // is logging turned off?

        // Timestamp
        $text = '['.date('m/d/Y g:i A').'] - ';
        $text .= $msg;

        // Write to log
        $fp = fopen($this->_ipnLogFile, 'a');
        fwrite($fp, $text . "\n\n");
        fclose($fp);  // close file
    }

    //Parse XML response from eway and place them into an array
    function parseResponse($xmlResponse) {
        $xml_parser = xml_parser_create();
        xml_parse_into_struct($xml_parser, $xmlResponse, $xmlData, $index);
        $responseFields = array();
        foreach ($xmlData as $data){
            if (isset($data["value"])){
            $responseFields[$data["tag"]] = $data["value"];
            }
        }
        return $responseFields;
    }
}